const path = require('path');
const fs = require('fs');
const Image = require('../models/Image');

exports.uploadImage = async (ctx) => {
  const file = ctx.request.files?.file; // 前端字段名为 "file"
  if (!file) {
    ctx.status = 400;
    ctx.body = { error: 'No file uploaded' };
    return;
  }

  try {



    fs.renameSync(file.filepath, path.join(__dirname, '../uploads', file.originalFilename));


    ctx.status = 201;
    ctx.body = {
      message: 'File uploaded successfully',
      name: file.originalFilename,
      // url: `http://${ctx.host}/images/${}`
    };
  } catch (error) {
    // 出错时删除已上传的文件
    console.log(error);
    
    fs.unlinkSync(file.filepath);
    ctx.status = 500;
    ctx.body = { error: 'Internal server error' };
  }
};

// exports.getImage = async (ctx) => {
//   const { id } = ctx.params;
  
//   try {
//     const image = await Image.findByPk(id);
//     if (!image) {
//       ctx.status = 404;
//       ctx.body = { error: 'Image not found' };
//       return;
//     }

//     ctx.type = image.mimetype;
//     ctx.body = fs.createReadStream(image.path);
//   } catch (error) {
//     ctx.status = 500;
//     ctx.body = { error: 'Internal server error' };
//   }
// };

